<template>
  <div>
    <DaprPlusTable
      :table-title="$t('daprplus.auth.resource.list')"
      :entity="entity"
      :grid-options="gridOptions"
      :form-options="formOptions"
      :query-api="(query) => getResourcePageApi(query, service)"
      :create-api="(dtos) => createResourcesApi(dtos, service)"
      :update-api="(dtos) => updateResourcesApi(dtos, service)"
      :delete-api="(ids) => deleteResourcesApi(ids, service)"
      :default-new-record="createDefaultResource"
      :show-search-form="true"
      @update:grid-api="onGridApiUpdate"
    >
      <template #action="{ row }">
        <Button
          type="link"
          @click="openEditOperationsModal(row)"
          v-if="row.allowedOperations && row.allowedOperations.length > 0"
        >
          <template #icon><SettingOutlined /></template>
        </Button>
      </template>
      <template #allowedOperations_default="{ row }">
        <div class="operation-tags">
          <Tag
            v-for="op in row.allowedOperations"
            :key="op.code"
            :color="op.color || 'default'"
            class="operation-tag"
          >
            {{ op.display }}
          </Tag>
          <span
            v-if="!row.allowedOperations || row.allowedOperations.length === 0"
            class="no-operations"
          >
            {{ $t('daprplus.auth.resource.noOperationsShort') }}
          </span>
        </div>
      </template>
    </DaprPlusTable>

    <!-- 编辑操作模态框 -->
    <EditAllowedOperationsModal
      v-model:open="editOperationsModalVisible"
      :resource="currentResource"
      :service="service"
      @success="onOperationsUpdated"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import type {
  ExtendedVxeGridApi,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { VbenFormProps } from '#/adapter/form';
import { DaprPlusTable } from '#/components/daprplus';
import { createBooleanColumn, type EntityInfo } from '#/utils/daprplus';
import { Tag, Button } from 'ant-design-vue';
import { SettingOutlined } from '@ant-design/icons-vue';
import {
  type ResourceInDto,
  type ResourceOutDto,
  type ServiceName,
  ResourceType,
  ResourceAccessType,
  getResourcePageApi,
  createResourcesApi,
  updateResourcesApi,
  deleteResourcesApi,
} from '#/api/daprplus/auth/resource';
import {
  resourceTypeOptions,
  accessTypeOptions,
  serviceInfoDict,
} from '#/utils/daprplus';
import EditAllowedOperationsModal from './EditAllowedOperationsModal.vue';
import { $t } from '#/locales';

const entity: EntityInfo = {
  code: 'Resource',
  display: $t('daprplus.auth.resource.title'),
};

// 将枚举字典转换为数组项
const resourceTypeOptionsArray = Object.entries(resourceTypeOptions).map(
  ([key, value]) => ({
    value: Number(key),
    label: value.label,
    color: value.color,
  }),
);

const accessTypeOptionsArray = Object.entries(accessTypeOptions).map(
  ([key, value]) => ({
    value: Number(key),
    label: value.label,
    color: value.color,
  }),
);

// 当前选择的服务名称
const selectedService = ref<ServiceName>('IdentityApi');

// 根据选择的服务名称计算URL前缀
const service = computed(() => {
  return serviceInfoDict[selectedService.value]?.value || 'identity-api';
});

// 验证规则
const validRules = {
  name: [
    { required: true, message: '资源名称不能为空' },
    { min: 2, max: 50, message: '资源名称长度应在2-50个字符之间' },
  ],
  code: [
    { required: true, message: '资源代码不能为空' },
    { min: 2, max: 200, message: '资源代码长度应在2-200个字符之间' },
  ],
  serviceName: [
    { required: true, message: '服务名称不能为空' },
    { min: 2, max: 50, message: '服务名称长度应在2-50个字符之间' },
  ],
  description: [{ max: 500, message: '描述长度不能超过500个字符' }],
};

// 配置搜索表单
const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'RadioGroup',
      label: '服务名称',
      fieldName: 'serviceName',
      defaultValue: 'IdentityApi',
      componentProps: {
        options: Object.entries(serviceInfoDict).map(([key, info]) => ({
          label: info.label,
          value: key as ServiceName,
        })),
        onChange: (value: any) => {
          // 如果 value 是事件对象，则从 value.target.value 中获取实际值
          const actualValue =
            typeof value === 'object' && value !== null && 'target' in value
              ? (value.target as any).value
              : value;

          // 确保 actualValue 是 ServiceName 类型
          if (
            typeof actualValue === 'string' &&
            ['IdentityApi', 'SoftwaresApi', 'GamesApi'].includes(actualValue)
          ) {
            selectedService.value = actualValue as ServiceName;
          }
        },
      },
    },
    {
      component: 'Input',
      label: '资源名称',
      fieldName: 'name',
    },
    {
      component: 'Input',
      label: '资源代码',
      fieldName: 'code',
    },
    {
      component: 'Select',
      label: '资源类型',
      fieldName: 'type',
      componentProps: {
        options: resourceTypeOptionsArray,
      },
    },
    {
      component: 'Select',
      label: '访问类型',
      fieldName: 'accessType',
      componentProps: {
        options: accessTypeOptionsArray,
      },
    },
    {
      component: 'VbenCheckbox',
      label: '系统资源',
      fieldName: 'isSystem',
    },
    {
      component: 'VbenCheckbox',
      label: '已锁定',
      fieldName: 'isLocked',
    },
  ],
  showCollapseButton: true,
  submitOnChange: true,
};

// 表格配置
const gridOptions: VxeTableGridOptions<ResourceOutDto> = {
  editRules: validRules,
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
  },
  columns: [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '编号',
      sortable: true,
      width: 130,
    },
    {
      field: 'name',
      title: '资源名称',
      sortable: true,
      align: 'left',
      minWidth: 120,
      editRender: { name: 'input' },
    },
    {
      field: 'code',
      title: '资源代码',
      align: 'left',
      minWidth: 250,
      editRender: { name: 'input' },
    },
    {
      field: 'serviceName',
      title: '服务名称',
      align: 'left',
      width: 120,
      editRender: { enabled: false },
    },
    {
      field: 'type',
      title: '资源类型',
      width: 100,
      editRender: {
        name: 'select',
        options: resourceTypeOptionsArray,
      },
    },
    {
      field: 'accessType',
      title: '访问类型',
      width: 100,
      editRender: {
        name: 'select',
        options: accessTypeOptionsArray,
      },
    },
    {
      field: 'description',
      title: '描述',
      align: 'left',
      minWidth: 200,
      visible: false,
      editRender: { name: 'input' },
    },
    {
      field: 'allowedOperations',
      title: '允许的操作',
      minWidth: 250,
      visible: true,
      slots: { default: 'allowedOperations_default' },
      editRender: { enabled: false },
    },
    createBooleanColumn('isSystem', '系统资源', {
      editRender: { enabled: false },
    }),
    createBooleanColumn('isLocked', '已锁定'),
    {
      field: 'operate',
      title: '操作',
      width: 120,
      slots: { default: 'action' },
      fixed: 'right',
    },
  ],
};

let gridApi: ExtendedVxeGridApi;

function onGridApiUpdate(api: ExtendedVxeGridApi) {
  gridApi = api;
}

// 创建默认资源
function createDefaultResource(): ResourceInDto {
  return {
    id: '0',
    name: '新资源',
    code: 'Resource.Code',
    serviceName: selectedService.value,
    type: ResourceType.Api,
    accessType: ResourceAccessType.None,
    description: '',
    isLocked: false,
    metadata: {},
    allowedOperations: [],
  };
}

// 编辑操作模态框相关
const editOperationsModalVisible = ref(false);
const currentResource = ref<ResourceOutDto>({} as ResourceOutDto);

// 打开编辑操作模态框
function openEditOperationsModal(row: ResourceOutDto) {
  currentResource.value = row;
  editOperationsModalVisible.value = true;
}

// 操作更新成功后的回调
function onOperationsUpdated() {
  // 刷新表格数据
  if (gridApi) {
    gridApi.reload();
  }
}
</script>

<style scoped>
.resource-operations {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin-top: 8px;
}

.operation-title {
  font-weight: bold;
  margin-bottom: 8px;
}

.operation-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.operation-tag {
  margin: 2px;
  cursor: default;
}

.no-operations {
  color: #999;
  font-style: italic;
  font-size: 12px;
}
</style>
